//
//  BGToast.m
//  FirstDemo
//
//  Created by 边果互动 on 2021/3/4.
//

#import "BGToast.h"

#define textFont [UIFont systemFontOfSize: 14]

@interface BGToast ()

@property(nonatomic, strong) UIView* rootView;

@end

@implementation BGToast

+(instancetype) makeToast: (UIView *) rootView andMsg:(NSString *) msg {
    return [[self alloc] initWithRootAndMsg:rootView andMsg:msg];
}

-(instancetype) initWithRootAndMsg:(UIView *)rootView andMsg:(NSString *)msg {
    _rootView = rootView;
    if (self = [super init]) {
        self.backgroundColor = [UIColor blackColor];
        self.alpha = 0;
        self.layer.cornerRadius = 10;
        self.layer.masksToBounds = YES;
        self.textColor = [UIColor whiteColor];
        self.text = msg;
        self.textAlignment = NSTextAlignmentCenter;
        //重点：这样设置才会自动换行
        self.numberOfLines = 0;
        self.font = textFont;
        CGFloat rootW = rootView.frame.size.width;
        CGFloat rootH = rootView.frame.size.height;
        CGSize size = [self sizeWithText:msg];
        CGFloat viewW = size.width + 20;
        CGFloat viewH = size.height + 10;
        CGFloat viewX = (rootW - viewW) / 2;
        CGFloat viewY = (rootH - viewH) / 2;
        self.frame = CGRectMake(viewX, viewY, viewW, viewH);
    }
    return self;
}

-(void) show {
    if (self.isShowing) {
        return;
    }
    self.isShowing = true;
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0.5;
    } completion:^(BOOL finished) {
        if (finished) {
            [UIView animateWithDuration:0.5 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
                self.alpha = 0;
            } completion:^(BOOL finished) {
                if (finished) {
                    [self removeFromSuperview];
                    self.isShowing = false;
                }
            }];
        }
    }];
    [_rootView addSubview:self];
}

#pragma mark - 计算一个字符串的size，可以用来计算TextView的宽高
-(CGSize) sizeWithText: (NSString *) text {
    return [self sizeWithText:text andMaxSize:CGSizeMake(250, MAXFLOAT) andFont:textFont];
}

#pragma mark - 通过字体和最大宽高来计算一个字符串的size，可以用来计算TextView的宽高
-(CGSize) sizeWithText: (NSString *) text andMaxSize: (CGSize) maxSize andFont: (UIFont *) font {
    NSDictionary *attr = @{NSFontAttributeName : font};
    //参数一：表示设置的最大宽和高
    //参数二：暂时先固定用这个，记住
    //参数三：一个字典，里面放一个字体，
    //注意：这里的字体一定要和UILabelView设置的字体是一样的
    CGSize size = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
    return size;
}
@end
